package com.ljm.sys.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljm.common.enums.DataStatus;
import com.ljm.common.enums.ResultStatus;
import com.ljm.common.excuption.Assert;
import com.ljm.common.page.PageDto;
import com.ljm.common.util.BeanUtils;
import com.ljm.common.util.PageUtil;
import com.ljm.common.util.StringUtil;
import com.ljm.sys.auth.api.SysAuthUserRoleApi;
import com.ljm.sys.auth.entity.SysAuthUserRole;
import com.ljm.sys.auth.mapper.SysAuthUserRoleMapper;
import com.ljm.sys.auth.service.ISysAuthUserRoleService;
import com.ljm.sys.org.dto.SysOrgUserDto;
import com.ljm.sys.org.entity.SysOrgUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
    * 系统用户角色关联 服务实现类
    * </p>
 *
 * @author HuamingChen
 * @since 2019-02-25
 */
@Service
@Transactional
public class SysAuthUserRoleServiceImpl extends ServiceImpl<SysAuthUserRoleMapper, SysAuthUserRole>
        implements ISysAuthUserRoleService, SysAuthUserRoleApi {
    /**
     * 角色关联数据数据接口
     */
    @Resource
    private SysAuthUserRoleMapper sysAuthUserRoleMapper;

    @Override
    public void bathDel(List<Long> ids) {
        if(StringUtil.isEmpty(ids)){
            Assert.throwException(ResultStatus.FIAL.getCode(),"请选择要删除的数据");
        }
        this.removeByIds(ids);
    }

    @Override
    public void delByUserId(Long userId) {
        QueryWrapper<SysAuthUserRole> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        this.remove(wrapper);
    }

    @Override
    public void roleRefUser(String roleCode, List<Long> userIds, SysOrgUserDto userDto){
        if(!StringUtil.isEmpty(userIds)){
            List<SysAuthUserRole> pos=new ArrayList<>();
            userIds.forEach(userId->{
                // 排重
                if(!this.checkRefRoleUser(roleCode,userId)){
                    SysAuthUserRole po=new SysAuthUserRole();
                    po.setCreateTime(LocalDateTime.now());
                    po.setCreater(userDto.getLoginName());
                    po.setStatus(DataStatus.NORMAL.getCode());
                    po.setOrgId(userDto.getOrgId());
                    po.setEditor(userDto.getLoginName());
                    po.setEditTime(LocalDateTime.now());
                    po.setRoleCode(roleCode);
                    po.setUserId(userId);
                    pos.add(po);
                }
            });
            this.saveBatch(pos);
        }
    }

    private boolean checkRefRoleUser(String roleCode,Long userId){
        QueryWrapper<SysAuthUserRole> wrapper=new QueryWrapper<>();
        wrapper.eq("role_code",roleCode);
        wrapper.eq("user_id",userId);
        return this.count(wrapper)>0 ? true : false;
    }

    @Override
    public Set<String> getDataByUserId(Long userId) {
        Set<String> dtos=new HashSet<>();
        QueryWrapper<SysAuthUserRole> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysAuthUserRole> pos=this.list(wrapper);
        if(!StringUtil.isEmpty(pos)){
            pos.stream().forEach(po->
                   dtos.add(po.getRoleCode()) );
        }
        return dtos;
    }

    @Override
    public void userRefRole(List<String> roleCodes, Long userId, SysOrgUserDto userDto) {
        if(StringUtil.isEmpty(roleCodes)){
            // 删除已经关联的数据
            this.delByUserId(userId);
        }else{
            this.delByUserId(userId);
            List<SysAuthUserRole> pos=new ArrayList<>();
            roleCodes.forEach(roleCode->{
                SysAuthUserRole po=new SysAuthUserRole();
                po.setCreateTime(LocalDateTime.now());
                po.setCreater(userDto.getLoginName());
                po.setStatus(DataStatus.NORMAL.getCode());
                po.setOrgId(userDto.getOrgId());
                po.setEditor(userDto.getLoginName());
                po.setEditTime(LocalDateTime.now());
                po.setRoleCode(roleCode);
                po.setUserId(userId);
                pos.add(po);
            });
            this.saveBatch(pos);
        }
    }

    @Override
    public PageDto<SysOrgUserDto> getRefUserByPage(String roleCode, String loginName, String realName, String email, Integer pageNo, Integer pageSize) {
        PageDto<SysOrgUserDto> pageDto=new PageDto<>(pageNo,pageSize);
        Integer total=sysAuthUserRoleMapper.getRefUserRows(roleCode,loginName,realName,email);
        if(total>0){
            List<SysOrgUser> list=sysAuthUserRoleMapper.getRefUserList(roleCode,loginName,realName,email, PageUtil.getStartRow(pageNo,pageSize),pageSize);
            if(!StringUtil.isEmpty(list)){
                pageDto.setTotal(total);
                pageDto.setRecords(BeanUtils.copyPropertiesByList(list,SysOrgUserDto.class));
            }
        }
        return pageDto;
    }
}
